// 路由管理
import {
  createRouter,
  createWebHistory,
  createWebHashHistory,
} from 'vue-router'
const routes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('../components/login/login.vue'),
    meta: { isAuth: true, title: '登录' },
    beforeEnter: (to, from, next) => {
      if (to.meta.isAuth) {
        //判断是否需要授权
        if (localStorage.getItem('user') == null) {
          next() //放行
        }
      }
    },
  },
  {
    path: '/',
    name: 'home',
    component: () => import('../components/home/home.vue'),
    meta: {
      isAuth: true,
      title: '商品管理系统-首页',
    },
    redirect: '/user', // 重定向到用户信息
    children: [
      {
        path: '/user',
        name: 'user',
        component: () => import('../components/home/user.vue'),
        meta: {
          isAuth: true,
          title: '个人信息',
        },
      },
      {
        path: '/shop',
        name: 'shop',
        component: () => import('../components/shop/shop.vue'),
        meta: {
          isAuth: true,
          title: '商品管理',
        },
      },
    ],
  },
]
const router = createRouter({
  //createWebHashHistory()  不需要后端配合  类似于a标签的描点连接
  history: createWebHistory(),
  routes,
})

// 全局导航守卫 (切换路由前)
router.beforeEach((to, from, next) => {
  //获取浏览器里存储的token信息
  const token = localStorage.getItem('token')
  //没有token则应该删除用户的信息
  if (!token) {
    //清除所有缓存信息
    localStorage.clear()
    //不是登录页，强制要求跳转到登录页
    if (to.path !== '/login') {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
})
// 全局导航守卫 (切换路由后)
router.afterEach((to, from) => {})

export default router
